import { createRouter, createWebHistory } from 'vue-router'
import LoginPage from '@/views/login/LoginPage.vue'
import Layout from '@/views/layout/LayoutContainer.vue'
import { usePermissionStore } from '@/stores/index.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginPage
    },
    {
      path: '/',
      name: 'layout',
      component: Layout,
      children: []
    }
  ]
})
/**
 * 1.查看用户是否登录
 *      1.1 如果用户没有登录，则不做路由操作
 *      1.2 如果用户已经登录，则判断是否路由是否已加载，未加载则加载路由
 */
router.beforeEach(async (to) => {
  if (to.path === '/login') return
  let { needLoadRoutes, getRoutes } = usePermissionStore()
  if (needLoadRoutes) {
    let routes = await getRoutes()
    routes.forEach(route => {
      // console.log(route)
      route.path = '/'+route.path
      router.addRoute(route)
    })
    return { ...to, replace: true }
  }
})
export default router
